import {useMessage} from "/@/hooks/message";

const ajaxUtils = (options: any) => {
    return new Promise((resolve, reject) => {
        options.type = options.type || "POST";
        options.url = options.url || "";
        options.timeout = options.timeout || 5000;
        options.onComplete = options.onComplete || function () {
        };
        options.onError = options.onError || function () {
        };
        options.onSuccess = options.onSuccess || function () {
        };
        options.data = options.data || null;

        let xml;
        if (typeof XMLHttpRequest !== "undefined") {
            xml = new XMLHttpRequest();
        } else if (typeof ActiveXObject !== "undefined") {
            let aVersions = [
                "Microsoft.XMLHTTP",
                "Msxml2.XMLHttp.6.0",
                "Msxml2.XMLHttp.5.0",
                "Msxml2.XMLHttp.4.0",
                "Msxml2.XMLHttp.3.0",
            ];
            for (let i = 0; i < aVersions.length; i++) {
                try {
                    // eslint-disable-next-line no-undef
                    xml = new ActiveXObject(aVersions[i]);
                    break;
                    // eslint-disable-next-line no-empty
                } catch (e) {
                }
            }
        }

        if (!xml) {
            reject(new Error("Ajax不受支持"));
            return;
        }

        xml.open(options.type, options.url, true);

        let timeoutLength = options.timeout;

        let requestDone = false;

        setTimeout(function () {
            requestDone = true;
        }, timeoutLength);

        xml.onreadystatechange = function () {
            if (xml.readyState === 4 && !requestDone) {
                if (httpSuccess(xml)) {
                    resolve(httpData(xml));
                } else {
                    reject({
                        status: xml.status,
                        statusText: "硬件调用请求服务失败，请重试",
                    });
                }

                options.onComplete();

                xml = null;
            } else {
                if (xml.status === 500 || xml.status === 404 || xml.status === 0) {
                    reject({
                        status: xml.status,
                        statusText: "500请求失败，请重试",
                    });
                }
            }
        };
        xml.send(options.data);
    });
}

const httpSuccess = (r: any) => {
    try {
        return (
            (!r.status && location.protocol === "file:") ||
            (r.status >= 200 && r.status <= 300) ||
            r.status === 304 ||
            (navigator.userAgent.indexOf("Safari") >= 0 &&
                typeof r.status === "undefined")
        );
    } catch (e) {
        return false;
    }
}

const httpData = (r: any) => {
    try {
        let contentType = r.getResponseHeader("content-type") || "";
        if (contentType.indexOf("json") !== -1) {
            return JSON.parse(r.responseText);
        } else if (contentType.indexOf("xml") !== -1) {
            return r.responseXML;
        } else {
            return r.responseText;
        }
    } catch (e) {
        return null;
    }
}

// 读卡
export const readCardDevice = async () => {
    return await ajaxUtils({
        type: "GET",
        url: "http://127.0.0.1:23366/readCard",
    }).then((data: any) => {
        if (data.code === 0) {
            return {code: 0, msg: "读卡成功", data: data.data.card_number}
        } else {
            useMessage().warning(data.msg)
            return {code: 1, msg: data.msg, data: null}
        }
    }).catch((err) => {
        useMessage().warning("读卡失败:" + err.statusText)
        return {code: 1, msg: err.statusText, data: null}
    });
}

/**
 * 打印
 * @param resData 打印数据
 * @param printCode 打印模板
 */
export const printDevice = async (resData: any, printCode: any) => {
    let obj = {
        json: {
            v1: resData.itemName, //项目队列名称
            v2: resData.patientNo, //序列号
            v3: resData.customerName, //姓名
            v4: resData.customerAge, //年龄
            v5: resData.localCard, //卡号
            v6: resData.pregnantWeek, //孕周
            v7: resData.address, //检查地点
            v8: resData.waitNum, //候诊人数
            v9: resData.checkNumber, //检查编号
            v10: resData.examBodyPart, //检查部位
            v11: resData.examMethod, //检查途径
            v12: resData.registrationTime, //登记时间
            v13: resData.warmReminder, //温馨提示
        },
        url: "192.168.0.103:9999",
        QCode: resData.localCard, //卡号一维码
        qrCode: "https://wxgzh.fckyy.org.cn/api/WeChatServer/RedirectUrl?uri=https%3A%2F%2Fwxgzh.fckyy.org.cn%2Fauth%3Fredirect_uri%3D%252Fmyqueue", //卡号二维码
        templateName: printCode, //打印模板名称
    };
    let params = "";
    for (let key in obj) {
        if (key === "json") {
            params += `${key}=${JSON.stringify(obj[key])}&`;
            continue;
        }
        params += `${key}=${obj[key]}&`;
    }
    params = params.substring(0, params.length - 1);
    return await ajaxUtils({
        type: "GET",
        url: "http://127.0.0.1:23366/print?" + params,
        timeout: 30000,
    }).then((data: any) => {
        if (data.code === 0) {
            return {code: 0, msg: "打印成功", data: null}
        } else {
            useMessage().warning(data.msg)
            return {code: 1, msg: data.msg, data: null}
        }
    }).catch((err) => {
        useMessage().warning("打印失败:" + err.statusText)
        return {code: 1, msg: err.statusText, data: null}
    });
}



